import ajax from 'uni-ajax'
import env from '../env'
import store from '../store/index.js'

// console.log(env.baseURL, 'base', store.state.userInfo.token)
// Default configuration
const _ajax = ajax.create({
  baseURL: env.baseURL,
  header: {
    // Authorization: `Bearer ${store.state.userInfo.token}`,
    post: {
      'Content-Type': 'application/json'
    }
  }
})

_ajax.interceptors.request.use(
  request => {
    request.header.Authorization = `Bearer ${uni.getStorageSync('jyToken')}`
    return request
  },
  error => {
    // Do something with request error
    return error
  }
)

_ajax.interceptors.response.use(
  response => {
    // Do something with response data
    const data = response.data
    // console.log(data.code, 'response code')
    if (data && data.code === 401) {
      // console.log(data, 'auth 401')
      // uni.removeStorageSync('jyToken')
      store.commit('logout')
      uni.navigateTo({
        url: '/pages/login/index'
      })
      return
    }
    return response
  },
  error => {
    uni.showToast({
      title: 'error'
    })
    // Do something with response error
    return error
  }
)

export default _ajax
